package com.fast.common.util;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

public class DESUtil {

	private static final String CHARSET = "UTF-8";

	public static String encrypt(String message) {
		try {
			Key localKey = getSecKey(getKey());
			SecureRandom sr = getRadom(getKey());
			Cipher localCipher = Cipher.getInstance("DES");
			localCipher.init(Cipher.ENCRYPT_MODE, localKey, sr);
			byte[] dest = localCipher.doFinal(message.getBytes(CHARSET));
			return Hex.encodeHexString(dest);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new RuntimeException(ex.getMessage(), ex);
		}
	}

	/**
	 * 字符串解密
	 * 
	 * @param String
	 * @return String
	 */
	public static String decrypt(String message) {
		try {
			Key local = getSecKey(getKey());
			SecureRandom sr = getRadom(getKey());
			Cipher localCipher = Cipher.getInstance("DES");
			localCipher.init(Cipher.DECRYPT_MODE, local, sr);
			byte[] dest = localCipher.doFinal(Hex.decodeHex(message.toCharArray()));
			return new String(dest, CHARSET);

		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage(), ex);
		}
	}

	private static SecureRandom getRadom(String key) throws Exception {
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
		sr.setSeed(key.getBytes(CHARSET));
		return sr;
	}

	private static String getKey() {
		return "	";
	}

	private static Key getSecKey(String key) throws Exception {
		byte[] keys = Base64.encodeBase64(key.getBytes(CHARSET));
		DESKeySpec dks = new DESKeySpec(keys);
		// 创建一个密钥工厂，然后用它把DESKeySpec转换成SecretKey对象
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		return securekey;
	}
}
